<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="decorator" content="default"/>
    <title>统计管理</title>
	<link rel="stylesheet" href="/css/font-awesome.min.6.4.css">
    <link rel="stylesheet" href="/css/main.css">
    <link th:href="@{/css/plugins/echarts/echarts.css}" rel="stylesheet">
    <link th:href="@{/css/pm/statistics.css}" rel="stylesheet">
</head>
<body>
    <div class="statistics-container">
        <!-- 页面标题和导出按钮 -->
        <div class="page-header">
            <h1 class="page-title">
                <i class="fa fa-bar-chart"></i> 统计管理
            </h1>
            <div class="export-section">
                <button type="button" class="btn btn-info" onclick="goToReportView()" style="margin-right: 10px;">
                    <i class="fa fa-file-text"></i> 查看报表
                </button>
            </div>
        </div>
        
        <!-- 顶部统计卡片 -->
        <div class="stats-container">
            <div class="stat-card">
                <div class="stat-icon projects">
                    <i class="fa fa-folder-open"></i>
                </div>
                <div class="stat-info">
                    <h3 th:text="${projectStats[0].count}">0</h3>
                    <p th:text="${projectStats[0].name}">总项目数</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon issues">
                    <i class="fa fa-exclamation-circle"></i>
                </div>
                <div class="stat-info">
                    <h3 th:text="${issueStats[0].count}">0</h3>
                    <p th:text="${issueStats[0].name}">总需求数</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon progress">
                    <i class="fa fa-cogs"></i>
                </div>
                <div class="stat-info">
                    <h3 th:text="${projectStats[1].count}">0</h3>
                    <p th:text="${projectStats[1].name}">进行中项目</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon pending">
                    <i class="fa fa-clock"></i>
                </div>
                <div class="stat-info">
                    <h3 th:text="${issueStats[1].count}">0</h3>
                    <p th:text="${issueStats[1].name}">待处理需求</p>
                </div>
            </div>
        </div>
        
        <!-- 图表区域 -->
        <div class="charts-container">
            <div class="chart-card">
                <div class="chart-header">
                    <h3>项目统计</h3>
                </div>
                <div class="chart-container">
                    <div id="projectChart" style="height: 300px;"><div style="text-align: center; padding: 50px;"><div class="loading-spinner"></div><p style="margin-top: 10px; color: #666;">加载中...</p></div></div>
                </div>
            </div>
            <div class="chart-card">
                <div class="chart-header">
                    <h3>需求统计</h3>
                </div>
                <div class="chart-container">
                    <div id="issueChart" style="height: 300px;"><div style="text-align: center; padding: 50px;"><div class="loading-spinner"></div><p style="margin-top: 10px; color: #666;">加载中...</p></div></div>
                </div>
            </div>
        </div>
        
        <!-- 大型统计图表 -->
        <div class="large-chart-container">
            <div class="large-chart-header">
                <h3>项目需求分布</h3>
            </div>
            <div class="large-chart">
                <div id="distributionChart" style="height: 400px;"><div style="text-align: center; padding: 50px;"><div class="loading-spinner"></div><p style="margin-top: 10px; color: #666;">加载中...</p></div></div>
            </div>
        </div>
        
        <!-- 需求状态和优先级统计 -->
        <div class="charts-container">
            <div class="chart-card">
                <div class="chart-header">
                    <h3>需求状态统计</h3>
                </div>
                <div class="chart-container">
                    <div id="statusChart" style="height: 300px;"><div style="text-align: center; padding: 50px;"><div class="loading-spinner"></div><p style="margin-top: 10px; color: #666;">加载中...</p></div></div>
                </div>
            </div>
            <div class="chart-card">
                <div class="chart-header">
                    <h3>需求优先级统计</h3>
                </div>
                <div class="chart-container">
                    <div id="priorityChart" style="height: 300px;"><div style="text-align: center; padding: 50px;"><div class="loading-spinner"></div><p style="margin-top: 10px; color: #666;">加载中...</p></div></div>
                </div>
            </div>
        </div>
    </div>

	<th:block th:include="include :: footer" />
    <!-- ECharts -->
    <script th:src="@{/js/plugins/echarts/echarts.min.js}"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            // 设置默认日期范围（最近30天）
            setDefaultDateRange();
            
            // 确保DOM完全加载后再初始化图表
            setTimeout(function() {
                initCharts();
            }, 100);
        });
        
        // 设置默认日期范围
        function setDefaultDateRange() {
            var endDate = new Date();
            var startDate = new Date();
            startDate.setDate(startDate.getDate() - 30);
            
            $('#startDate').val(formatDate(startDate));
            $('#endDate').val(formatDate(endDate));
        }
        
        // 格式化日期为YYYY-MM-DD
        function formatDate(date) {
            var year = date.getFullYear();
            var month = String(date.getMonth() + 1).padStart(2, '0');
            var day = String(date.getDate()).padStart(2, '0');
            return year + '-' + month + '-' + day;
        }
        
        // 跳转到报表查看页面
        function goToReportView() {
            window.location.href = ctx + 'statistics/report/view';
        }
        
        // 预览报表数据
        function previewReport() {
            var startDate = $('#startDate').val();
            var endDate = $('#endDate').val();
            var reportType = $('#reportType').val();
            
            if (!startDate || !endDate) {
                $.modal.alert('请选择开始时间和结束时间');
                return;
            }
            
            if (new Date(startDate) > new Date(endDate)) {
                $.modal.alert('开始时间不能晚于结束时间');
                return;
            }
            
            $.modal.loading("正在加载预览数据...");
            
            $.ajax({
                url: ctx + "statistics/report/preview",
                type: "get",
                data: {
                    startDate: startDate,
                    endDate: endDate,
                    reportType: reportType
                },
                success: function(result) {
                    $.modal.closeLoading();
                    if (result.code == 0) {
                        displayPreviewData(result.data, reportType);
                    } else {
                        $.modal.alert(result.msg || '获取预览数据失败');
                    }
                },
                error: function() {
                    $.modal.closeLoading();
                    $.modal.alert('获取预览数据失败，请检查网络连接');
                }
            });
        }
        
        // 显示预览数据
        function displayPreviewData(data, reportType) {
            if (!data || data.length === 0) {
                $('#previewData').html('<div class="text-center text-muted">暂无数据</div>');
                $('#previewSection').show();
                return;
            }
            
            // 只显示前5条数据
            var previewData = data.slice(0, 5);
            
            // 获取表头
            var headers = Object.keys(previewData[0]);
            
            var html = '<table class="table table-sm table-bordered">';
            
            // 表头
            html += '<thead><tr>';
            headers.forEach(function(header) {
                html += '<th>' + header + '</th>';
            });
            html += '</tr></thead>';
            
            // 数据行
            html += '<tbody>';
            previewData.forEach(function(row) {
                html += '<tr>';
                headers.forEach(function(header) {
                    var value = row[header] || '';
                    // 处理过长的文本
                    if (String(value).length > 50) {
                        value = String(value).substring(0, 50) + '...';
                    }
                    html += '<td title="' + value + '">' + value + '</td>';
                });
                html += '</tr>';
            });
            html += '</tbody></table>';
            
            // 显示总数据条数
            html += '<div class="text-muted small mt-2">共 ' + data.length + ' 条数据，此处显示前5条</div>';
            
            $('#previewData').html(html);
            $('#previewSection').show();
        }
        
        // 导出报表
        function exportReport() {
            var startDate = $('#startDate').val();
            var endDate = $('#endDate').val();
            var reportType = $('#reportType').val();
            var format = $('#format').val();
            
            if (!startDate || !endDate) {
                $.modal.alert('请选择开始时间和结束时间');
                return;
            }
            
            if (new Date(startDate) > new Date(endDate)) {
                $.modal.alert('开始时间不能晚于结束时间');
                return;
            }
            
            $.modal.loading("正在生成报表，请稍候...");
            
            // 创建表单进行提交
            var form = $('<form>', {
                method: 'post',
                action: ctx + 'statistics/report/export'
            });
            
            $('<input>').attr({
                type: 'hidden',
                name: 'startDate',
                value: startDate
            }).appendTo(form);
            
            $('<input>').attr({
                type: 'hidden',
                name: 'endDate',
                value: endDate
            }).appendTo(form);
            
            $('<input>').attr({
                type: 'hidden',
                name: 'reportType',
                value: reportType
            }).appendTo(form);
            
            $('<input>').attr({
                type: 'hidden',
                name: 'format',
                value: format
            }).appendTo(form);
            
            form.appendTo('body').submit().remove();
            
            // 3秒后关闭加载提示（假设文件生成需要时间）
            setTimeout(function() {
                $.modal.closeLoading();
                $('#exportModal').modal('hide');
                $.modal.msgSuccess('报表导出成功！');
            }, 3000);
        }
        
        // 安全初始化所有图表
        function initCharts() {
            console.log("initCharts");
            // 检查每个图表容器是否存在且可见
            var projectChart = document.getElementById('projectChart');
            var issueChart = document.getElementById('issueChart');
            var distributionChart = document.getElementById('distributionChart');
            var statusChart = document.getElementById('statusChart');
            var priorityChart = document.getElementById('priorityChart');
            
            console.log("容器检查:", {
                projectChart: !!projectChart,
                issueChart: !!issueChart,
                distributionChart: !!distributionChart,
                statusChart: !!statusChart,
                priorityChart: !!priorityChart
            });
            
            // 如果容器存在，初始化图表
            if (projectChart) {
                initProjectChart();
            }
            if (issueChart) {
                initIssueChart();
            }
            if (distributionChart) {
                initDistributionChart();
            }
            if (statusChart) {
                initStatusChart();
            }
            if (priorityChart) {
                initPriorityChart();
            }
        }
        
        // 显示加载动画
        function showLoadingAnimations() {
            $('.chart-container').each(function() {
                var container = $(this);
                container.html('');
            });
        }
        
        // 项目统计图表
        function initProjectChart() {
            var chartElement = document.getElementById('projectChart');
            console.log("项目统计图表容器:", chartElement);
            if (!chartElement) {
                console.log("项目统计图表容器不存在");
                return;
            }
            
            var timeoutId = setTimeout(function() {
                $('#projectChart').html('<div style="text-align: center; padding: 50px; color: #999;">数据加载超时，请刷新页面重试</div>');
            }, 10000);
            
            $.ajax({
                url: ctx + "statistics/projectChartData",
                type: "get",
                timeout: 8000,
                beforeSend: function() {
                    $('#projectChart').html('<div style="text-align: center; padding: 50px;"><div class="loading-spinner"></div><p style="margin-top: 10px; color: #666;">加载项目统计数据...</p></div>');
                },
                success: function(result) {
                    clearTimeout(timeoutId);
                    console.log("项目统计数据返回:", result);
                    
                    if (result && result.code == 0 && result.data) {
                        try {
                            var chart = echarts.init(chartElement);
                            var option = {
                                backgroundColor: '#fff',
                                tooltip: {
                                    trigger: 'item',
                                    formatter: "{a} <br/>{b}: {c} ({d}%)"
                                },
                                legend: {
                                    orient: 'vertical',
                                    left: 10,
                                    top: 'center',
                                    textStyle: {
                                        fontSize: 12
                                    }
                                },
                                series: [{
                                    name: '项目统计',
                                    type: 'pie',
                                    radius: ['45%', '65%'],
                                    center: ['60%', '50%'],
                                    avoidLabelOverlap: false,
                                    label: {
                                        show: false,
                                        position: 'center'
                                    },
                                    emphasis: {
                                        label: {
                                            show: true,
                                            fontSize: '16',
                                            fontWeight: 'bold'
                                        }
                                    },
                                    labelLine: {
                                        show: false
                                    },
                                    data: result.data.labels.map(function(label, index) {
                                        var colors = ['#667eea', '#764ba2', '#f093fb', '#f5576c', '#4facfe'];
                                        return {
                                            name: label, 
                                            value: result.data.data[index],
                                            itemStyle: {
                                                color: colors[index % colors.length]
                                            }
                                        };
                                    })
                                }]
                            };
                            chart.setOption(option);
                            
                            // 窗口大小变化时重绘图表
                            $(window).on('resize', function() {
                                chart.resize();
                            });
                        } catch (error) {
                            console.error("项目统计图表初始化错误:", error);
                            $('#projectChart').html('<div style="text-align: center; padding: 50px; color: #f56c6c;">图表初始化失败</div>');
                        }
                    } else {
                        $('#projectChart').html('<div style="text-align: center; padding: 50px; color: #999;">暂无项目统计数据</div>');
                    }
                },
                error: function(xhr, status, error) {
                    clearTimeout(timeoutId);
                    console.error("项目统计数据请求错误:", error);
                    $('#projectChart').html('<div style="text-align: center; padding: 50px; color: #f56c6c;">数据加载失败: ' + error + '</div>');
                }
            });
        }
        
        // 需求统计图表
        function initIssueChart() {
            var chartElement = document.getElementById('issueChart');
            if (!chartElement) return;
            
            $.ajax({
                url: ctx + "statistics/issueChartData",
                type: "get",
                beforeSend: function() {
                    $('#issueChart').html('<div style="text-align: center; padding: 50px;"><div class="loading-spinner"></div></div>');
                },
                success: function(result) {
                    if (result.code == 0) {
                        var chart = echarts.init(chartElement);
                        var option = {
                            backgroundColor: '#fff',
                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'shadow'
                                },
                                formatter: function(params) {
                                    return params[0].name + '<br/>' + params[0].seriesName + ': ' + params[0].value;
                                }
                            },
                            grid: {
                                left: '3%',
                                right: '4%',
                                bottom: '3%',
                                containLabel: true
                            },
                            xAxis: {
                                type: 'category',
                                data: result.data.labels,
                                axisLine: {
                                    lineStyle: {
                                        color: '#ccc'
                                    }
                                },
                                axisLabel: {
                                    color: '#666'
                                }
                            },
                            yAxis: {
                                type: 'value',
                                axisLine: {
                                    lineStyle: {
                                        color: '#ccc'
                                    }
                                },
                                axisLabel: {
                                    color: '#666'
                                }
                            },
                            series: [{
                                name: '需求数量',
                                type: 'bar',
                                barWidth: '60%',
                                data: result.data.data,
                                itemStyle: {
                                    color: function(params) {
                                        var colorList = ['#4facfe', '#00f2fe', '#667eea', '#764ba2', '#f093fb'];
                                        return colorList[params.dataIndex % colorList.length];
                                    }
                                },
                                emphasis: {
                                    itemStyle: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }]
                        };
                        chart.setOption(option);
                        
                        // 窗口大小变化时重绘图表
                        $(window).on('resize', function() {
                            chart.resize();
                        });
                    }
                }
            });
        }
        
        // 项目需求分布图表
        function initDistributionChart() {
            var chartElement = document.getElementById('distributionChart');
            if (!chartElement) return;
            
            $.ajax({
                url: ctx + "statistics/projectIssueDistribution",
                type: "get",
                beforeSend: function() {
                    $('#distributionChart').html('<div style="text-align: center; padding: 50px;"><div class="loading-spinner"></div></div>');
                },
                success: function(result) {
                    if (result.code == 0) {
                        var chart = echarts.init(chartElement);
                        var projectNames = result.data.map(function(item) { return item.project_name; });
                        var issueCounts = result.data.map(function(item) { return item.issue_count; });
                        
                        var option = {
                            backgroundColor: '#fff',
                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'shadow'
                                },
                                formatter: function(params) {
                                    return params[0].name + '<br/>需求数量: ' + params[0].value;
                                }
                            },
                            grid: {
                                left: '3%',
                                right: '4%',
                                bottom: '15%',
                                containLabel: true
                            },
                            xAxis: {
                                type: 'category',
                                data: projectNames,
                                axisLine: {
                                    lineStyle: {
                                        color: '#ccc'
                                    }
                                },
                                axisLabel: {
                                    interval: 0,
                                    rotate: 45,
                                    color: '#666',
                                    fontSize: 12
                                }
                            },
                            yAxis: {
                                type: 'value',
                                axisLine: {
                                    lineStyle: {
                                        color: '#ccc'
                                    }
                                },
                                axisLabel: {
                                    color: '#666'
                                }
                            },
                            series: [{
                                name: '需求数量',
                                type: 'bar',
                                barWidth: '50%',
                                data: issueCounts,
                                itemStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: '#83bff6' },
                                        { offset: 0.5, color: '#188df0' },
                                        { offset: 1, color: '#188df0' }
                                    ])
                                },
                                emphasis: {
                                    itemStyle: {
                                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                            { offset: 0, color: '#2378f7' },
                                            { offset: 0.7, color: '#2378f7' },
                                            { offset: 1, color: '#83bff6' }
                                        ])
                                    }
                                }
                            }]
                        };
                        chart.setOption(option);
                        
                        // 窗口大小变化时重绘图表
                        $(window).on('resize', function() {
                            chart.resize();
                        });
                    }
                }
            });
        }
        
        // 需求状态统计图表
        function initStatusChart() {
            var chartElement = document.getElementById('statusChart');
            if (!chartElement) return;
            
            $.ajax({
                url: ctx + "statistics/issueStatusStats",
                type: "get",
                beforeSend: function() {
                    $('#statusChart').html('<div style="text-align: center; padding: 50px;"><div class="loading-spinner"></div></div>');
                },
                success: function(result) {
                    if (result.code == 0) {
                        var chart = echarts.init(chartElement);
                        var option = {
                            backgroundColor: '#fff',
                            tooltip: {
                                trigger: 'item',
                                formatter: "{a} <br/>{b}: {c} ({d}%)"
                            },
                            legend: {
                                orient: 'vertical',
                                left: 10,
                                top: 'center',
                                textStyle: {
                                    fontSize: 12
                                },
                                data: result.data.map(function(item) { return item.status_name; })
                            },
                            series: [{
                                name: '需求状态',
                                type: 'pie',
                                radius: ['40%', '60%'],
                                center: ['60%', '50%'],
                                data: result.data.map(function(item, index) {
                                    var colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57', '#ff9ff3', '#54a0ff'];
                                    return {
                                        name: item.status_name, 
                                        value: item.issue_count,
                                        itemStyle: {
                                            color: colors[index % colors.length]
                                        }
                                    };
                                }),
                                emphasis: {
                                    itemStyle: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                },
                                label: {
                                    formatter: '{b}: {c} ({d}%)'
                                }
                            }]
                        };
                        chart.setOption(option);
                        
                        // 窗口大小变化时重绘图表
                        $(window).on('resize', function() {
                            chart.resize();
                        });
                    }
                }
            });
        }
        
        // 需求优先级统计图表
        function initPriorityChart() {
            var chartElement = document.getElementById('priorityChart');
            if (!chartElement) return;
            
            $.ajax({
                url: ctx + "statistics/issuePriorityStats",
                type: "get",
                beforeSend: function() {
                    $('#priorityChart').html('<div style="text-align: center; padding: 50px;"><div class="loading-spinner"></div></div>');
                },
                success: function(result) {
                    if (result.code == 0) {
                        var chart = echarts.init(chartElement);
                        var option = {
                            backgroundColor: '#fff',
                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'shadow'
                                },
                                formatter: function(params) {
                                    return params[0].name + '<br/>需求数量: ' + params[0].value;
                                }
                            },
                            grid: {
                                left: '3%',
                                right: '4%',
                                bottom: '3%',
                                containLabel: true
                            },
                            xAxis: {
                                type: 'category',
                                data: result.data.map(function(item) { return item.priority_name; }),
                                axisLine: {
                                    lineStyle: {
                                        color: '#ccc'
                                    }
                                },
                                axisLabel: {
                                    color: '#666'
                                }
                            },
                            yAxis: {
                                type: 'value',
                                axisLine: {
                                    lineStyle: {
                                        color: '#ccc'
                                    }
                                },
                                axisLabel: {
                                    color: '#666'
                                }
                            },
                            series: [{
                                name: '需求数量',
                                type: 'bar',
                                barWidth: '60%',
                                data: result.data.map(function(item) { return item.issue_count; }),
                                itemStyle: {
                                    color: function(params) {
                                        var colorList = ['#ff6b6b', '#feca57', '#ff9ff3', '#54a0ff', '#5f27cd'];
                                        return colorList[params.dataIndex % colorList.length];
                                    }
                                },
                                emphasis: {
                                    itemStyle: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }]
                        };
                        chart.setOption(option);
                        
                        // 窗口大小变化时重绘图表
                        $(window).on('resize', function() {
                            chart.resize();
                        });
                    }
                }
            });
        }
    </script>
</body>
</html>